package org.jvending.provisioning.portal;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jvending.provisioning.stocking.handler.StockingHandler;
import org.jvending.provisioning.stocking.StockingContext;
import org.jvending.provisioning.stocking.StockingException;
import org.jvending.provisioning.stocking.ProviderContext;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.util.logging.Logger;
import java.util.List;
import java.util.Iterator;
import java.io.IOException;

public class ParStocker extends HttpServlet {

    Logger logger = Logger.getLogger("ParStocker");

    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        logger.info("POST");
        ServletRequestContext requestContext = new ServletRequestContext(request);
        boolean isMultipart = FileUpload.isMultipartContent(requestContext);
        if (!isMultipart) {
            logger.info("This content is not multipart content");
        }

        FileItemFactory fileItemfactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemfactory);
        List fileItems;
        try {
            fileItems = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
            return;//TODO: send to error page
        }

        StockingContext stockingContext = (StockingContext)
                this.getServletContext().getAttribute("org.jvending.provisioning.stocking.StockingContext");
        if(stockingContext == null)
        {
           logger.severe("Missing Stocking Context");
        }
        StockingHandler stockingHandler;
        try {
            stockingHandler = stockingContext.getStockingHandler("GENERIC");
        } catch (StockingException e) {
            e.printStackTrace();
            return;//TODO: Send to error page
        }

        ProviderContext providerContext = stockingContext.getProviderContext(request);

        for (Iterator i = fileItems.iterator(); i.hasNext();) {
            FileItem fileItem = (FileItem) i.next();
            try {
                stockingHandler.addParFile(fileItem.getInputStream(), providerContext);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            this.getServletContext().getRequestDispatcher("/display-catalog").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
